<?php

namespace App\Admin\Controllers;

use App\Models\Purchase;
use App\Models\InventoryFunc;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Widgets\Form as myForm;


class PurchaseController extends Controller
{
    use ModelForm;
    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('采购');
            $content->description('');

            $content->body($this->grid());
        });
    }


    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('采购');
            $content->description('');

            $content->body($this->form());
        });
    }

    public function destroy($id)
    {
        if ($this->form()->destroy($id)) {
            return response()->json([
                'status'  => true,
                'message' => trans('admin.delete_succeeded'),
            ]);
        } else {
            return response()->json([
                'status'  => false,
                'message' => trans('admin.delete_failed'),
            ]);
        }
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Purchase::class, function (Grid $grid) {
            $grid->model()->select('company.name','supplier.name as supplier_name','warehouse.name as warehouse_name','operation.name as operation_name','purchase.*')
            ->leftjoin('company','company.id','=','purchase.company_id')
            ->leftjoin('supplier','supplier.id','=','purchase.supplier_id')
            ->leftjoin('warehouse','warehouse.id','=','purchase.warehouse_id')
            ->leftjoin('admin_users as operation','purchase.operater_id','=','operation.username')
            ->where('purchase.company_id',Admin::user()->company_id)
            ->orderBy('purchase.created_at', 'desc');
            $grid->id('采购单编号')->sortable();
            $grid->supplier_name('供应商名称');
            $grid->name('所属公司');
            $grid->operation_name('采购员');

//            if(Admin::user()->isRole('Purchase Amount')){
            if (Admin::user()->can('purchase.auditing')) {
                $grid->exchange_amount('汇率后含税价')->display(function($v){return round($v,2);});
                $grid->tax('税额')->display(function($v){return round($v,2);});
                $grid->exchange_rate('汇率');
                $grid->rate('税率')->display(function($v){return $v."%";});
                $grid->currency('结算币种')->display(function ($v){
                    return  HelpersController::getStateValue('currency',$v);
                });
            }

            // $grid->exchange_amount('汇率后含税价')->display(function($v){return round($v,2);});
            // $grid->tax('税额')->display(function($v){return round($v,2);});
            // $grid->exchange_rate('汇率');
            // $grid->rate('税率')->display(function($v){return $v."%";});

            //$grid->created_at('创建时间');
            //$grid->updated_at('更新时间');
            //$grid->sendTime('到货时间');
            //$grid->bar_code('条形码url');
            $grid->warehouse_name('仓库编号');
            $grid->pay_type('付款方式')->display(function($v){
                return HelpersController::getStateValue('payType',$v);
            });
            $grid->purchase_state('采购单状态')->display(function($v){
                return HelpersController::getStateValue('purchaseState',$v);
            });
            $grid->payment_state('付款状态')->display(function($v){
                return HelpersController::getStateValue('paymentState',$v);
            });
            $grid->review_state("审核状态")->display(function($v){
                return HelpersController::getStateValue('purchaseReviewState',$v);
            });
            $grid->disableExport();//禁用导出按钮

            //$grid->paid_amount('已付金额');
            //$grid->purchase_type('采购单类型');
            //$grid->remark('备注');
            $grid->actions(function ($actions) {
                // append一个操作
                $actions->disableDelete();//禁用编辑
                $actions->disableEdit();
                $actions->prepend('<a href="'.\Route('purchases.show',['id'=>$actions->getKey()]).'"><i class="fa fa-eye"></i></a>');
            });
            // $grid->actions(function ($actions) {
            //     // append一个操作
            //     $actions->disableEdit();
            //     $actions->disableDelete();//禁用编辑
            //     $actions->prepend('<a href="'.\Route('purchases.show',['id'=>$actions->getKey()]).'"><i class="fa fa-eye"></i></a>');
            // });

            $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();

                $filter->where(function ($query) {
                    $query->where('purchase.id', 'like', "%{$this->input}%");
                }, '采购单编号');

                $filter->where(function ($query) {
                    $query->where('supplier.name', 'like', "%{$this->input}%");
                }, '供应商名称');

                $filter->where(function ($query) {
                    $query->where('operation.name','like',"%{$this->input}%");
                }, '采购员');

            });

        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        Admin::script('
            var supplier_id;
            $(document).off("change",".sku_id");
            $(document).on("change",".sku_id", function(e){
                var sku_id = $(this).val();
                var pdom =  $(this).parents(".has-many-fakeModel-form");
                if(!sku_id){

                    return;
                }
                supplier_id= $(".supplier_id").val();
                if(!supplier_id){
                    $("#myModalLabel").text("警告")
                    $(".modal-body").text("请先维护供应商")
                    $("#myModal").modal()
                    return
                }
                $.ajax({
                  method: "POST",
                  url: "/purchase/ajaxSkuOtherInfos",
                  data: { sku_id: sku_id, supplier_id: supplier_id }
                }).success(function( msg ) {
                  msg = JSON.parse(msg);
                    pdom.find(".thick").removeAttr("required");
                    pdom.find(".origin").removeAttr("required");
                    pdom.find(".grade").removeAttr("required");
                    pdom.find(".avg_size").removeAttr("required");
                    pdom.find(".min_size").removeAttr("required");
                    pdom.find(".colour").next(".select2-container").css("border","1px solid #d2d6de").removeAttr("required");
                    pdom.find(".thick").next(".select2-container").css("border","1px solid #d2d6de");
                    pdom.find(".origin").next(".select2-container").css("border","1px solid #d2d6de");
                    pdom.find(".grade").next(".select2-container").css("border","1px solid #d2d6de");
                    pdom.find(".avg_size").next(".select2-container").css("border","1px solid #d2d6de");
                    pdom.find(".min_size").next(".select2-container").css("border","1px solid #d2d6de");
                    pdom.find(".colour").next(".select2-container").css("border","1px solid #d2d6de");
                  if(msg.price){
                    pdom.find(".price").val(msg.price);
                    pdom.find(".supplier_product_id").val(msg.id);
                  }else{
                    alert("尚未维护该sku的采购价")
                    pdom.find(".price").val("");
                    pdom.find(".supplier_product_id").val("");
                  }
                  if(msg.attribute){
                    var attr =  msg.attribute.split(",");
                    for(i in attr){
                        pdom.find("."+attr[i]).attr("required","required");
                        pdom.find("."+attr[i]).next(".select2-container").css("border","1px solid red");
                    }
                  }else{
                    alert("尚未维护该sku的批次属性");
                  }
                });
            });
            $(document).off("change",".supplier_id");
            $(document).on("change",".supplier_id",function(){
                supplier_id= $(".supplier_id").val();
                $.ajax({
                  method: "POST",
                  url: "/purchase/supplierInfo",
                  data: { supplier_id: supplier_id }
                }).success(function( msg ) {
                  msg = JSON.parse(msg);
                  if(msg){
                    $(".rate").val(msg.rate);
                    $(".currency_name").val(msg.currency_name)
                    $(".currency").val(msg.currency);
                  }else{
                    $(".rate").val("");
                    $(".currency").val("");
                    $(".currency_name").val("");

                  }
                });
            })
            $(document).off("change",".price");
            $(document).on("change",".price",function(){
                var exchange_rate= $(".exchange_rate").val();
                var pdom =  $(this).parents(".has-many-fakeModel-form");
                if(!exchange_rate){
                    $("#myModalLabel").text("警告")
                    $(".modal-body").text("请先维护汇率")
                    pdom.find(".price").val("");
                    pdom.find(".exprice").val("");
                    $("#myModal").modal()
                    return;
                }else{
                    pdom.find(".exprice").val( ( exchange_rate * $(this).val() ).toFixed(2) );
                }
            })
            $(document).off("change",".exprice");
            $(document).on("change",".exprice",function(){
                var exchange_rate= $(".exchange_rate").val();
                var pdom =  $(this).parents(".has-many-fakeModel-form");
                if(!exchange_rate){
                    $("#myModalLabel").text("警告")
                    $(".modal-body").text("请先维护汇率")
                    pdom.find(".price").val("");
                    pdom.find(".exprice").val("");
                    $("#myModal").modal()
                    return;
                }else{
                    pdom.find(".price").val( ( $(this).val()/exchange_rate ).toFixed(2) );
                }
            })
            $(document).off("change",".exchange_rate");
            $(document).on("change",".exchange_rate",function(){
                $(".price").val("");
                $(".exprice").val("");
            })
        ');
        return Admin::form(Purchase::class, function (Form $form) {

            $suppliers = \DB::table('supplier')->pluck('name','id');
            $form->radio('type','采购类型')->options(HelpersController::getStateOptions('purchaseType'));
            $form->select('supplier_id', '供应商编号')->options($suppliers);
            $form->text('contract_id', '合同订单编号')->help('合同订单编号可以不填写！');
            // $form->text('purchaseCompany_id', '采购公司编号');
            // $form->text('purchaser', '采购员');
            // $form->text('payStatus', '付款状态');
            // $form->text('purchaseStatus', '采购单状态');
            // $form->text('TotalAmount', '含税金额');
            // $form->text('tax', '税额');
            $form->rate('rate', '税率');
            $form->text('currency_name','结算货币')->attribute('readonly','readonly');
            $form->hidden('currency');
            // $form->datetime('send_time', '到货时间');
            $form->select('warehouse_id', '仓库编号')->options(\DB::table('warehouse')->where('company_id',Admin::user()->company_id)->pluck('name','id'));
            $form->text('exchange_rate','汇率');
            // $form->radio('pay_status', '付款方式')->options([0=>'全款',1=>'过程款']);
            $form->textarea('remark', '备注');
            $form->hasMany('fakeModel', function (Form\NestedForm $form) {
                $skus= \DB::table('sku')->pluck('name','id');
                $form->select('sku_id','sku')->options($skus);
                $form->text('supplier_product_id','供应商商品编号')->attribute(['readonly' => 'readonly']);
                $form->text('original_id','原始单据')->help('原始单据可以不填写！');
                $form->text('cowhide_id','皮源编号')->help('皮源编号可以不填写！');
                $form->text('price','单价（人民币）');
                $form->text('exprice','单价（汇率价）');
                $form->currency('size','尺寸')->symbol(' ');
                $form->number('num','张数');
                $form->datetime('arrive_time','到货时间');
                $form->select('grade','等级')->options(\DB::table('batchattribute')->where('parent_id','grade')->pluck('name','id'));
                $form->select('thick','厚度')->options(\DB::table('batchattribute')->where('parent_id','thick')->pluck('name','id'));
                $form->select('origin','产地')->options(\DB::table('batchattribute')->where('parent_id','origin')->pluck('name','id'));
                $form->select('colour','颜色')->options(\DB::table('batchattribute')->where('parent_id','colour')->pluck('name','id'));
                $form->select('min_size','最小尺寸')->options(\DB::table('batchattribute')->where('parent_id','min_size')->pluck('name','id'));
                $form->select('avg_size','平均尺寸')->options(\DB::table('batchattribute')->where('parent_id','avg_size')->pluck('name','id'));
            });
            $form->html('<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
    </div>
  </div>
</div>');
        });
    }

    public function ajaxSkuOtherInfos(Request $req){
        $arr = $req->all();
        $res = json_decode(json_encode(\DB::table('supplier_goods_price_bill')->where(['sku_id'=>$arr['sku_id'],'supplier_id'=>$arr['supplier_id'],'status'=>0])->orderBy('created_at','desc')->first()), true);
        $sku = \DB::table('sku')->where(['id'=>$arr['sku_id'],'status'=>0])->first();
        if($sku){
            if(json_decode($sku->batchattribute)){
                // dd(json_decode($sku->batchattribute));
                $res['attribute'] = implode(",",json_decode($sku->batchattribute));
            }else{
                $res['attribute'] = implode(",",json_decode(\DB::table('category')->where(['id'=>$sku->category_id,'status'=>0])->value('batchattribute')));
            }
        }
        return json_encode($res);
    }
    public function supplierInfo(Request $req){
        $arr = $req->all();
        $res = \DB::table('supplier')->where('id',$arr['supplier_id'])->first();
        $res = json_decode(json_encode($res),true);
        $res['currency_name'] = HelpersController::getStateValue('currency',$res['currency']);
        return json_encode($res);
    }
    public function store(Request $req){
        if(!$req['fakeModel']){
            admin_toastr('没有产生sku单据','error');
            return back()->withInput();
        }
        if(!$req['supplier_id']){
            admin_toastr('没有维护供应商资料','error');
            return back()->withInput();
        }

        // if($req['currency']<=0){
        //     admin_toastr('结算货币未维护','error');
        //     return back()->withInput();
        // }

        if($req['rate']<0){
            admin_toastr('税率至少大于等于0','error');
            return back()->withInput();
        }
        if($req['exchange_rate']<=0){
            admin_toastr('汇率至少大于0','error');
            return back()->withInput();
        }
        if(!$req['warehouse_id']){
            admin_toastr('仓库未维护','error');
            return back()->withInput();
        }

        // if(strtotime($input['send_time']) <= strtotime(date("Y-m-d h:i:s"))){
        //     admin_toastr('到货时间过早','error');
        //     return back()->withInput();
        // }

        $id = HelpersController::getId('purchase_id','P');
        $purchaseDetails = [];
        $total_amount  = 0;
        foreach ($req['fakeModel'] as $purchaseDetailArr) {
            if(!$purchaseDetailArr['sku_id']){continue;}
            if($purchaseDetailArr['price']<=0){
                admin_toastr('价格存在空值','error');
                return back()->withInput();
            }
            if($purchaseDetailArr['num']<=0){
                admin_toastr('张数存在空值','error');
                return back()->withInput();
            }
            if($purchaseDetailArr['size']<=0){
                admin_toastr('尺数存在空值','error');
                return back()->withInput();
            }

            if(strtotime($purchaseDetailArr['arrive_time']) < strtotime(date("Y-m-d")." 00:00:00")){
                admin_toastr('存在出货时间早于今天的sku详细','error');
                return back()->withInput();
            }
            $purchaseDetail['purchase_id'] = $id;
            $purchaseDetail['sku_id'] = $purchaseDetailArr['sku_id'];
            $purchaseDetail['price'] = $purchaseDetailArr['price'];
            $purchaseDetail['num'] = $purchaseDetailArr['num'];
            $purchaseDetail['size'] = $purchaseDetailArr['size'];
            $purchaseDetail['grade'] = $purchaseDetailArr['grade'];
            $purchaseDetail['thick'] = $purchaseDetailArr['thick'];
            $purchaseDetail['origin'] = $purchaseDetailArr['origin'];
            $purchaseDetail['colour'] = $purchaseDetailArr['colour'];
            $purchaseDetail['min_size'] = $purchaseDetailArr['min_size'];
            $purchaseDetail['avg_size'] = $purchaseDetailArr['avg_size'];
            $purchaseDetail['supplier_product_id'] = $purchaseDetailArr['supplier_product_id'];
            $purchaseDetail['arrive_time'] = $purchaseDetailArr['arrive_time'];
            $purchaseDetail['created_at'] =  date('Y-m-d H:i:s');
            $total_amount += $purchaseDetailArr['price']*$purchaseDetailArr['size'];

            array_push($purchaseDetails, $purchaseDetail);
        }
        if(!$purchaseDetails){
            admin_toastr('没有产生sku单据','error');
            return back()->withInput();
        }

        \DB::beginTransaction();
        $tax = $req['currency']=="CNY"?($total_amount*$req['rate']*0.01):0;
        $purchase = \DB::table('purchase')
            ->insert(
                [
                    'id' => $id,
                    'supplier_id'=>$req['supplier_id'],
                    'total_amount'=>$total_amount,
                    'exchange_amount'=>$total_amount*$req['exchange_rate'],
                    'exchange_rate'=>$req['exchange_rate'],
                    'tax'=>$tax,
                    'rate'=>$req['rate'],
                    'warehouse_id' => $req['warehouse_id'],
                    'type' => $req['type'],
                    'remark' => $req['remark'],
                    'currency' => $req['currency'],
                    'updated_at' => date('Y-m-d H:i:s'),
                    'created_at' => date('Y-m-d H:i:s'),
                    'company_id' => Admin::user()->company_id,
                    'operater_id' => Admin::user()->username,
                    // 'review_state' => $review_state,
                ]
             );
        \DB::table('purchase_detail')
            ->insert($purchaseDetails);
        HelpersController::endId('purchase_id');

        \DB::commit();
        admin_toastr(trans('admin.save_succeeded'));

        $url = route('purchases.index');

        return redirect($url);
    }

    public function show($id)
    {
        $model = new Content();
        $data = \DB::table('purchase')->select(
            'purchase.*', 'supplier.name as supplier_name',
            'admin_users.name as user_name',
            'company.name as company_name',
            // 'documentary.name as documentary_name',
            // 'salesman.name as salesman',
            'reviewer.name as reviewer_name'
        )
            ->leftjoin('company', 'purchase.company_id', '=', 'company.id')
            ->leftjoin('supplier', 'purchase.supplier_id', '=', 'supplier.id')
            ->leftjoin('admin_users', 'admin_users.username', '=', 'purchase.operater_id')
            // ->leftjoin('admin_users as documentary','documentary.username','=','agent.merchandiser')
            // ->leftjoin('admin_users as salesman','salesman.username','=','agent.salesman')
            ->leftjoin('admin_users as reviewer', 'reviewer.username', '=', 'purchase.reviewer_id')
            ->where('purchase.id', $id)
            ->first();
        $detail_data = \DB::table('purchase_detail')->select('purchase_detail.*',
            'sku.name as sku_name',
            'batch_grade.name as batch_grade',
            'batch_thick.name as batch_thick',
            'batch_origin.name as batch_origin',
            'batch_colour.name as batch_colour',
            'batch_avg_size.name as batch_avg_size',
            'batch_min_size.name as batch_min_size')
            ->leftjoin('sku', 'purchase_detail.sku_id', '=', 'sku.id')
            ->leftjoin('batchattribute as batch_grade', 'purchase_detail.grade', '=', 'batch_grade.id')
            ->leftjoin('batchattribute as batch_thick', 'purchase_detail.thick', '=', 'batch_thick.id')
            ->leftjoin('batchattribute as batch_origin', 'purchase_detail.origin', '=', 'batch_origin.id')
            ->leftjoin('batchattribute as  batch_colour', 'purchase_detail.colour', '=', 'batch_colour.id')
            ->leftjoin('batchattribute as batch_avg_size', 'purchase_detail.avg_size', '=', 'batch_avg_size.id')
            ->leftjoin('batchattribute as batch_min_size', 'purchase_detail.min_size', '=', 'batch_min_size.id')
            ->where('purchase_detail.purchase_id', $id)->get();
        $content = '<div style="width:80%;margin:0 auto;background:#fff;padding:10px;"><div style="text-align:right;font-size:1.5rem;font-weight:700"><a style="" href="/admin/purchases">返回</a> | <a target="_blank" href="/admin/purchases/pdf/' . $id . '">打印采购单</a></div><h4 style="text-align:center;">基本信息</h4><hr>';
        $headers = [];
        // dd($data);
        $rows = [
            ['订单编号', $data->id,'合同订单编号', $data->contract_id],
            ['订单类型', HelpersController::getStateValue('inType',$data->type),'供应商编号', $data->supplier_name],
            ['所属公司', $data->company_name]
        ];
        $table_1 = new Table($headers, $rows);
        $content .= $table_1->render();


        $content .= '<h4 style="text-align:center;">系统信息</h4><hr>';

        // table 2
        $headers = [];
        $rows = [
            ['操作人', $data->user_name, '订单状态', HelpersController::getStateValue('purchaseState', $data->purchase_state)],
            // ['销售',isset($data->salesman)?$data->salesman:'未维护该客户销售','跟单', isset($data->documentary_name)?$data->documentary_name:'未维护该客户跟单' ],
            ['最后操作人', $data->reviewer_name, '最后操作时间', $data->review_time],
            ['生成时间', $data->created_at, '', '']

        ];
        $table2 = new Table($headers, $rows);
        $content .= $table2->render();

        $content .= "<h4 style='text-align:center'>sku信息</h4>";
        $headers = ['sku','供应商商品编号','原始单据','皮源编号','尺数','张数','到货时间','单价','等级','厚度','产地','颜色','平均尺寸','最小尺寸'];
        $rows = [];
        foreach($detail_data as $v){
            $row = [$v->sku_name,$v->supplier_product_id,$v->original_id,$v->cowhide_id,$v->size, $v->num,$v->arrive_time,$v->price,$v->batch_grade,$v->batch_thick,$v->batch_origin,$v->batch_colour,$v->batch_avg_size,$v->batch_min_size];
            array_push($rows, $row);
        }
        $table2 = new Table($headers, $rows);
        $content .= $table2->render();

        $content .= "<h4 style='text-align:center'>备注</h4><hr><p style='background:#efefef;padding:8px;'>" . (trim($data->remark) ? $data->remark : "无") . "</p>";

        $content .= '<h4 style="text-align:center;">财务状态</h4><hr>';

        //     tinyInteger('invoice')->nullable()->comment('是否开发票');
        //     decimal('invoice_money',11,4)->nullable()->comment('发票费用');

        // table 1

        // if($data->reviewer_id){
        $headers = [];
        $rows = [
            ['支付方式', HelpersController::getStateValue('payType', $data->pay_type),
                '支付状态', HelpersController::getStateValue('paymentState', $data->payment_state)],
            ['订单总价', round($data->total_amount, 2) , "已付款金额",
                round($data->paid_amount, 2) ],
            ['结算币种',HelpersController::getStateValue('currency',$data->currency)]
        ];
        $table = new Table($headers, $rows);
        $content .= $table->render();
        // }else{
        // $content .= '<p style="text-align:center;background:#efefef;padding:8px;">尚未维护</p>';
        // }

        if (Admin::user()->can('purchase.charge')) {
            $content .= '<h4 style="text-align:center;">主管审核</h4><hr>';
            switch ($data->review_state) {
                case "CREATED":
                    $form = new myForm();
                    $form->action($data->id . '/auditing');
                    $form->method('POST');
                    $form->disablePjax();
                    // echo view('admin::widgets.form', $form->getVariables())->render();
                    // $form->text('pay_type','支付方式');
                    $form->plus(["l_button" => "<input name='reject' class='btn btn-danger' type='submit' value='拒绝' />", "r_button" => "<input name='accept' class='btn btn-success' type='submit' value='通过' />"]);
                    $content .= $form->render();
                    break;
                case "FINISHED":
                    $content .= "<p style='background:#efefef;padding:8px;text-align:center'>订单已完成</p>";
                    break;
                case "INACTIVED":
                    $content .= "<p style='background:#efefef;padding:8px;text-align:center'>订单已取消</p>";
                    break;
                default:
                    $content .= "<p style='background:#efefef;padding:8px;text-align:center'>已审核</p>";
            }

        }
        if (Admin::user()->can('purchase.auditing')) {
            $content .= '<h4 style="text-align:center;">财务审核</h4><hr>';

            if ($data->review_state == "IN_CHECK" || $data->review_state == "FINANCE_LAST" || $data->review_state == "FINISHED") {
                $content .= <<<EOD
                        <p>进项税： $data->rate % ，汇率： $data->exchange_rate ：1</p>
                        <table class='table'>
                          <tr>
                            <th>sku</th>
                            <th>总入库尺寸</th>
                            <th>总入库张数</th>
                            <th>单价</th>
                            <th>入库总价</th>
                          </tr>
EOD;
                    // 注意 EOD;必须顶格
                $total_price = 0;
                foreach ($detail_data as $v) {
                    $actual_out = \DB::table('inventory_checking_detail')
                            ->select(\DB::raw('sum(size) as size'), \DB::raw('sum(num) as num'))
                            ->where(['checking_ASN' => $id, 'type' => 2, 'sku_id' => $v->sku_id, 'grade' => $v->grade, 'thick' => $v->thick, 'origin' => $v->origin, 'colour' => $v->colour, 'avg_size' => $v->avg_size, 'min_size' => $v->min_size])
                            ->first();
                    $total_price += $actual_out->size * $v->price;
                        $content .= "<tr><td>$v->sku_name</td><td>" . round($actual_out->size, 2) . "</td><td>" . round($actual_out->num, 2) . "</td><td>" . round($v->price, 2) . " </td><td>" . round($actual_out->size * $v->price, 2) . " </td></tr>";
                }
                $content .= "</table><p style='text-align:right'>合计（不含税）： $total_price </p>";
            }
            if ($data->payment_state == 2) {
                $content .= "<p style='background:#efefef;padding:8px;text-align:center'>订单已被标识为全款支付，如需变更请联系管理员</p>";
            } else {
                switch ($data->review_state) {
                    case "CHARGE_CHECK": //主管已审核
                        $form = new myForm();
                        $form->action($data->id . '/finance');
                        $form->method('POST');
                        $form->disablePjax();
                        $form->plus(["l_button" => "<input name='reject' class='btn btn-danger' type='submit' value='拒绝' />", "r_button" => "<input name='accept' class='btn btn-success' type='submit' value='通过' />"]);
                        $content .= $form->render();
                        break;
                    case "FINANCE_1ST": //订单已完成初审
                    case "IN_CHECK": //已入库
                        if (Admin::user()->can('purchase.pay')) {
                            $content .= '<table class="table table-bordered">
                                    <tr>
                                        <th>待付金额</th>
                                        <th>已付金额</th>
                                        <th>合计金额</th>
                                        <th>币种</th>
                                    </tr>
                                    <tr>
                                        <td class="WaitPayRMB">' . round(($data->exchange_amount - $data->exchange_paid_amount), 2) . '</td>
                                        <td>' . round($data->exchange_paid_amount, 2) . '</td>
                                        <td class="TotalPayRMB">' . round($data->exchange_amount, 2) . '</td>
                                        <td>本币</td>
                                    </tr>
                                    <tr>
                                        <td>' . round($data->total_amount - $data->paid_amount, 2) . '</td>
                                        <td>' . round($data->paid_amount, 2) . '</td>
                                        <td>' . round($data->total_amount, 2) . '</td>
                                        <td>外币</td>
                                    </tr>
                                </table>';
                            $form = new myForm();
                            $form->__construct(['exchange_rate' => $data->exchange_rate]);

                            $form->action($data->id . '/pay');
                            $form->method('POST');
                            $form->disablePjax();

                            $payType = HelpersController::getStateOptions('payType');
                            array_shift($payType);
                            $form->select('pay_type', '支付方式')->options($payType);
                            $form->text('exchange_rate', '汇率(外汇:本币)');
                            $form->text('exchange_paid_amount', '付款金额（本币）');
                            $form->text('paid_amount', '付款金额(外币)');
                            $form->plus(["l_button" => "<input class='btn btn-danger' type='reset' value='重置' />", "r_button" => "<input name='accept' class='btn btn-success' type='submit' value='提交付款' />"]);
                            $content .= $form->render();
                        }else{
                            $content .= "<p style='background:#efefef;padding:8px;text-align:center'>无付款权</p>";
                        }
                        if (Admin::user()->can('purchase.getAll')) {
                            $content .= "<hr><a href='javascript:void(0)' onclick='setAll()'>完成支付，标识为全款支付</a>";
                        }else{
                            $content .= "<p style='background:#efefef;padding:8px;text-align:center'>无结单权</p>";
                        }
                        break;
                    case "FINISHED":
                    case "FINANCE_LAST":
                        $content .= "<p style='background:#efefef;padding:8px;text-align:center'>订单已完成</p>";
                        break;
                    case "INACTIVED":
                        $content .= "<p style='background:#efefef;padding:8px;text-align:center'>订单已取消</p>";
                        break;
                    case "CREATED":
                        $content .= "<p style='background:#efefef;padding:8px;text-align:center'>主管尚未审核</p>";
                        break;
                    //                case "FINANCE_1ST":
                    //                    $content .="<p style='background:#efefef;padding:8px;text-align:center'>订单已审核</p>";
                    //                break;
                    default:
                        $content .= "<p style='background:#efefef;padding:8px;text-align:center'>订单状态异常，联系管理员！</p>";
                }
                $content .= '<script>
                    $(document).off("change",".exchange_rate");
                    $(document).on("change",".exchange_rate",function(){
                        var exchange_rate= $(".exchange_rate").val();
                        var totalPay =  ('.$data->exchange_paid_amount.' + '.($data->total_amount - $data->paid_amount).' * exchange_rate).toFixed(2);

                        var waitPay = (exchange_rate * '.($data->total_amount - $data->paid_amount).').toFixed(2);

                        $(".TotalPayRMB").text(totalPay);
                        $(".WaitPayRMB").text(waitPay);

                        $(".paid_amount").val("")
                        $(".exchange_paid_amount").val("")
                    })
                    $(document).off("change",".paid_amount");
                    $(document).on("change",".paid_amount",function(){
                        var exchange_rate= $(".exchange_rate").val();
                        $(".exchange_paid_amount").val(  ( $(this).val() * exchange_rate ).toFixed(2) )
                    })
                    $(document).off("change",".exchange_paid_amount");
                    $(document).on("change",".exchange_paid_amount",function(){
                        var exchange_rate= $(".exchange_rate").val();
                        $(".paid_amount").val(  ($(this).val()/exchange_rate).toFixed(2) )
                    })
                    function setAll(){
                        var r = confirm("注意，该操作并不会自动进行补价结算，请确认付款已全部操作结束")
                        if (r){
                            window.location.href="/admin/purchases/'.$data->id.'/setAll";
                        }
                    }
                </script>';
            }
        }
        $items = [
            'header'      => '采购单',
            'description' => 'purchase',
            'breadcrumb'  => '',
            'content'     => $content."</div>",
        ];

        return view('admin::content', $items)->render();
    }

    /**
     * 财务审核
     *
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Exception
     */
    public function finance($id){
        $input = \Illuminate\Support\Facades\Input::all();
        /**
         * laravel 表单验证
        $validator = \Validator::make($input, [
            'pay_type' => 'required',
            'payment_state'=>'required',
            'paid_amount'=>'required'
        ]);
        if ($validator->fails()) {
             return back()->withInput()->withErrors($validator->errors());
        }
         */
        unset($input['_token']);
        $input['reviewer_id'] = Admin::user()->username;
        $input['review_time'] = date('Y-m-d H:i:s');
        $old = \DB::table('purchase')->where('id',$id)->first();
        if($old->payment_state == 2){
            admin_toastr("订单已付全款,如要变更请联系系统管理员");
            return back()->withInput();
        }
        if($old->review_state == "FINANCE_1ST"){
            admin_toastr("订单已审核,如要变更请联系系统管理员");
            return back()->withInput();
        }
        if($old->review_state == "FINISHED" || $old->review_state == "FINANCE_LAST"){
            admin_toastr("订单已完成,如要变更请联系系统管理员");
            return back()->withInput();
        }
        $model = new InventoryFunc('purchase',$id);

        if(isset($input['accept'])){
            // 审核通过
            \DB::beginTransaction();
            try {
                $model->insertInventoryChecking()->insertBillsChecking($input);
                \DB::table('purchase')->where('id',$id)->update(['review_state'=>"FINANCE_1ST"]);
                \DB::commit();
                admin_toastr("审核处理成功");
                $url = route('purchases.index');
                return redirect($url);
            }catch (Exception $e) {
                \DB::rollBack();
                admin_toastr("数据库出错，请联系管理员","error");
                return back()->withInput();
            }
        }elseif(isset($input['reject'])){
            // 审核不通过

            $input['review_state'] = "INACTIVED";
            \DB::beginTransaction();
            try {
                \DB::table('purchase')->where('id',$id)->update(['review_state'=>"INACTIVED"]);
                $model->insertBillsChecking($input);
                \DB::commit();
            }catch (Exception $e) {
                \DB::rollBack();
                admin_toastr("数据库出错，请联系管理员","error");
                return back()->withInput();
            }
            admin_toastr("审核处理成功");
            $url = route('orders.index');
            return redirect($url);
        }else{
            admin_toastr('未知错误，请联系管理员','error');
            return back()->withInput();
        }
    }

    /**
     * 财务付款
     *
     * 每次审核都要修正汇率
     * (外币)
     * 已付金额 [paid_amount(total)] = 旧付款金额 + 新付款金额 [paid_amount(old) + paid_amount(input)]
     * 待付款金额 [wait_paid_amount(total)] = 单据金额 - 已付金额 [total_amount(old) - paid_amount(total)]
     * 总金额 = 单据金额 [total_amount(old)]
     * (本币)
     * 已付金额 [exchange_paid_amount(total)] = 旧付款金额 + 新付款金额 [exchange_paid_amount(old) + exchange_paid_amount(input)]
     * 待付款金额 [exchange_wait_paid_amount(total)] = 新汇率 * 未付款外币 [exchange_rate * wait_paid_amount(total)]
     * 总金额 [exchange_amount] = 已付金额 + 待付款金额 [exchange_paid_amount(total) + exchange_wait_paid_amount(total)]
     *
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Exception
     */
    public function pay($id){
        $input = \Illuminate\Support\Facades\Input::all();
        /**
         * laravel 表单验证
        $validator = \Validator::make($input, [
        'pay_type' => 'required',
        'payment_state'=>'required',
        'paid_amount'=>'required'
        ]);
        if ($validator->fails()) {
        return back()->withInput()->withErrors($validator->errors());
        }
         */
        unset($input['_token']);
        $input['reviewer_id'] = Admin::user()->username;
        $input['review_time'] = date('Y-m-d H:i:s');
        $old = \DB::table('purchase')->where('id',$id)->first();
        if($old->payment_state == 2){
            admin_toastr("订单已付全款,如要变更请联系系统管理员");
            return back()->withInput();
        }
        if($old->review_state == "FINISHED" || $old->review_state == "FINANCE_LAST"){
            admin_toastr("订单已完成,如要变更请联系系统管理员");
            return back()->withInput();
        }
        $model = new InventoryFunc('purchase',$id);

        if(isset($input['accept'])){
            // 存在付款按钮
            $input['review_state'] = "FINANCE_1ST";
            $input['payment_state'] = 1;
            unset($input['reject']);
            unset($input['accept']);
            \DB::beginTransaction();
            try {
                $model->insertBillsChecking($input);
                if(isset($input['exchange_rate']) && $input['exchange_rate'] != $old->exchange_rate){
                    $input['exchange_amount']  = $old->exchange_paid_amount +  ($old->total_amount  - $old->paid_amount) * $input['exchange_rate'];
                    if($old->currency == "CNY"){
                        $input['tax'] = $input['exchange_amount'] *  $old->rate;
                    }
                }
                $input['paid_amount'] += $old->paid_amount;
                $input['exchange_paid_amount'] += $old->exchange_paid_amount;

                \DB::table('purchase')->where('id',$id)->update($input);
                \DB::commit();
                admin_toastr("付款处理成功");
                $url = route('purchases.index');
                return redirect($url);
            }catch (Exception $e) {
                \DB::rollBack();
                admin_toastr("数据库出错，请联系管理员","error");
                return back()->withInput();
            }
        }else{
            admin_toastr('未知错误，请联系管理员','error');
            return back()->withInput();
        }
    }

    /**
     *  主管审核
     *
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Exception
     */
    public function auditing($id){
        $input = \Illuminate\Support\Facades\Input::all();
        $input['reviewer_id'] = Admin::user()->username;
        $input['review_time'] = date('Y-m-d H:i:s');
        $unNeedFinance = false;
        if(isset($input['accept'])){
            // 审核通过
            $input['review_state'] = "CHARGE_CHECK";
            if(\DB::table('purchase')->where('purchase.id',$id)->leftjoin('supplier','purchase.supplier_id','=','supplier.id')->value('supplier.type') == 1) {
                $input['review_state'] = "FINANCE_1ST";
                $unNeedFinance = true;
            }
        }elseif(isset($input['reject'])){
            // 审核不通过
            $input['review_state'] = "INACTIVED";
        }else{
            admin_toastr('未知错误，请联系管理员','error');
            return back()->withInput();
        }
        unset($input['accept']);
        unset($input['reject']);
        unset($input['_token']);
        $model = new InventoryFunc('purchase',$id);
        \DB::beginTransaction();
            try {
                \DB::table('purchase')->where('id',$id)->update($input);
                if($unNeedFinance){
                    $model->insertInventoryChecking();
                }
                $model->insertBillsChecking($input);
                \DB::commit();
            }catch (Exception $e) {
                \DB::rollBack();
                admin_toastr("数据库出错，请联系管理员","error");
                return back()->withInput();
            }
        admin_toastr('审核处理成功');
        $url = route('purchases.index');
        return redirect($url);
    }

    /**
     * 标识为全部付款
     *
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Exception
     */
    public function setAll($id){
        $input = [];
        $input['reviewer_id'] = Admin::user()->username;
        $input['review_time'] = date('Y-m-d H:i:s');
        $input['payment_state'] = 2;
//        $old = \DB::table('purchase')->where('id',$id)->first();
//        if($old->payment_state == 2){
//            admin_toastr("订单已付全款,如要变更请联系系统管理员");
//            return back()->withInput();
//        }
//        if($old->review_state == "FINISHED"){
//            admin_toastr("订单已完成,如要变更请联系系统管理员");
//            return back()->withInput();
//        }
        $model = new InventoryFunc('purchase',$id);
        \DB::beginTransaction();
        try {
            \DB::table('purchase')->where('id',$id)->update($input);
            $model->insertBillsChecking($input);
            \DB::commit();
        }catch (Exception $e) {
            \DB::rollBack();
            admin_toastr("数据库出错，请联系管理员","error");
            $url = route('purchases.index');
            return redirect($url);
        }
        admin_toastr('标识处理成功');
        $url = route('purchases.index');
        return redirect($url);
    }

    /**
     * 生成采购pdf单据
     *
     * @param $id
     * @return mixed
     */
    public function pdf($id){
        $purchase = \DB::table('purchase')->select('company.name','supplier.name as supplier_name','warehouse.name as warehouse_name','operation.name as operation_name','purchase.*')
            ->leftjoin('company','company.id','=','purchase.company_id')
            ->leftjoin('supplier','supplier.id','=','purchase.supplier_id')
            ->leftjoin('warehouse','warehouse.id','=','purchase.warehouse_id')
            ->leftjoin('admin_users as operation','purchase.operater_id','=','operation.username')
            ->where('purchase.id',$id)->first();
        $purchase_detail = \DB::table('purchase_detail')->select('purchase_detail.*',
            'sku.name as sku_name',
            'batch_grade.name as batch_grade',
            'batch_thick.name as batch_thick',
            'batch_origin.name as batch_origin',
            'batch_colour.name as batch_colour',
            'batch_avg_size.name as batch_avg_size',
            'batch_min_size.name as batch_min_size',
            'category.title')
            ->leftjoin('sku','purchase_detail.sku_id','=','sku.id')
            ->leftjoin('category','sku.category_id','=','category.id')
            ->leftjoin('batchattribute as batch_grade','purchase_detail.grade','=','batch_grade.id')
            ->leftjoin('batchattribute as batch_thick','purchase_detail.thick','=','batch_thick.id')
            ->leftjoin('batchattribute as batch_origin','purchase_detail.origin','=','batch_origin.id')
            ->leftjoin('batchattribute as  batch_colour','purchase_detail.colour','=','batch_colour.id')
            ->leftjoin('batchattribute as batch_avg_size','purchase_detail.avg_size','=','batch_avg_size.id')
            ->leftjoin('batchattribute as batch_min_size','purchase_detail.min_size','=','batch_min_size.id')
            ->where('purchase_detail.purchase_id',$id)->get();
        // dd($purchase_detail);
        $pdf = \App::make('snappy.pdf.wrapper');
        $title = $purchase->name;
        $url = public_path();
        $content = <<<EOD
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>{$title}采购订单</title>
</head>
<body>
    <style type="text/css">
        @font-face {
            font-family: msyh;
            src: url('$url/fonts/msyh.ttf') format('truetype');
        }
        * {
            font-family: msyh, DejaVu Sans,sans-serif;
        }
        h3{text-align: center;}
        table{vertical-align: middle;text-align: center;width:100%}
        .fl{float:left;width:25%;}
        .fl-title{float: left;width:50%;margin-bottom: 5px;font-weight: 700}
        .remark{position: relative;}
        .remark span{position: absolute;right:0;display: block;padding:30px 10px;background: rgb(255,153,204);font-size: .8rem;bottom:40px;color:#333;font-weight:700;border:2px solid #333;}
    </style>
    <h3>{$title}采购订单</h3>
    <div class="fl-title">需方： $purchase->name</div><div  class="fl-title">供方： $purchase->supplier_name</div>
    <table cellpadding="2" cellspacing="2" bgcolor="#666">
    <tbody bgcolor="#fff">
    <tr>
        <td rowspan="2">订单号</td>
        <td rowspan="2">产品编号</td>
        <td rowspan="2">种类</td>
        <td>皮胚厚度</td>
        <td rowspan="2">颜色</td>
        <td>数量</td>
        <td>含税单价</td>
        <td>金额</td>
        <td colspan="2">到厂时间</td>
        <td rowspan="2" width="30%">备注</td>
    </tr>
    <tr>
        <td>（mm）</td>
        <td>SF</td>
        <td>（元/SF）</td>
        <td>（元）</td>
        <td>要求</td>
        <td>确认</td>
    </tr>
EOD;
    $count = count($purchase_detail);
    foreach ($purchase_detail as $k => $detail) {
        if($k == 0){
           $content.='
    <tr>
        <td>'.$purchase->id.'</td>
        <td>'.$detail->sku_name.'</td>
        <td>'.$detail->title.'</td>
        <td>'.$detail->batch_thick.'</td>
        <td>'.$detail->batch_colour.'</td>
        <td>'.round($detail->size,2).'</td>
        <td>'.round($detail->price,2).'</td>
        <td>'.round($detail->size*$detail->price,2).'</td>
        <td></td>
        <td></td>
        <td rowspan ="'.$count.'">'.$purchase->remark.'</td>
    </tr>';
        }else{
            $content.='
    <tr>
        <td>'.$purchase->id.'</td>
        <td>'.$detail->sku_name.'</td>
        <td>'.$detail->title.'</td>
        <td>'.$detail->batch_thick.'</td>
        <td>'.$detail->batch_colour.'</td>
        <td>'.round($detail->size,2).'</td>
        <td>'.round($detail->price,2).'</td>
        <td>'.round($detail->size*$detail->price,2).'</td>
        <td></td>
        <td></td>
    </tr>';
        }

}
// dd($purchase);
$content.='
    </tbody>
</table>
<p class="remark">备注：<br/>
1、本订单中的皮革根据双方约定平均张幅不低于38SF，最小张幅不低于30SF,计量误差按国家标准不超过3%；<br/>
2、本订单中的皮革数量允许5%的溢装，不能短装；<br/>
3、本订单中的皮革单价为含17℅增值税和运费到需方工厂价；<br/>
4、交货期：本订单签订后<strong>准时交货（可分批交货）</strong>。货到QC检验后按入库数量付款。<br/>
5、本订单交货时，送货单必须注明供应商名称、产品批号及订单号，并送交我公司仓库签收；<br/>
6、本订单经双方签字盖章后即产生合同法律效力，否则视为无效；<br/>
7、本订单内容如需任何变动，均以书面通知为准；<br/>
8、本订单的纠纷解决：如有纠纷，双方尽量协商解决；如协商不成，可向所在地人民法院提起诉讼。
<span>请签字回传,表示收到此份订单,谢谢!</span>
</p>
<div class="fl-title">需方： '.$title.'</div><div  class="fl-title">供方： '.$purchase->supplier_name.'</div>
<div class="fl">制单：'.$purchase->operation_name.'<br><br>日期： '.$purchase->created_at.'</div><div  class="fl">审核：</div><div  class="fl">审批：</div><div  class="fl">（签字）：<br><br>日期：</div>
</body>
</html>
';
        // echo $content;
        $pdf->loadHTML($content);
        return $pdf->setPaper('a4')->setOrientation('landscape')->stream($title."采购单_".date('YmdHi'));
    }
}